const promise = require('./wx_promise.js')
const Constant = require('./const')
const theme = require("../theme.config.js")

function requestUrl(path) {
  let url = ''
  //不是以http://或者https://开头的就拼接host
  if (!/^(http(s)?\:\/\/)/.test(path)) {
    url = `${theme.host}${path}`
  } else {
    url = path
  }
  return url
}

class Http {

    doGet(path, data) {
        //var url = theme.host + path
        var url = requestUrl(path)

        return this._request('GET', url, data)
    }

    doPost(path, data) {
        //var url = theme.host + path
        var url = requestUrl(path)

        return this._request('POST', url, data)
    }

    _request(method, url, data) {
        const obj = {
            url,
            method,
            data,
        }
        if (method == "POST") {
          if (data.header) {
            obj.header = data.header
            delete data.header
          } else {
            obj.header = {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            }
          }
        }
        theme.debug && console.log("发送请求:", obj)
        return promise(wx.request)(obj)
            .then(res => {
                const result = res.data
                theme.debug && console.log("收到数据:", result)
                let msg = result.msg || result.message
                if (msg && msg != "success") {
                    throw result
                }
                return result
            })
    }
}

module.exports = new Http();